﻿using Grow.Db.Repository;
using Grow.Db.UnitOfWork;
using Grow.EventBus.Cap.Enum;
using Grow.EventBus.Cap.PublisherEventData;
using Grow.Module.Service;
using Grow.Scheduler.Job;

namespace Grow.EventBus.Cap.Job
{
    public class ExpirerPublisherEventDataJob : JobBase
    {
        private readonly IUnitOfWorkManager _unitOfWorkManager;
        private readonly IRepository<PublisherEventDataEntity> _publisherEventDataRepository;
        public ExpirerPublisherEventDataJob(IServiceContext serviceContext) : base(serviceContext)
        {
            _unitOfWorkManager = serviceContext.GetRequiredService<IUnitOfWorkManager>();
            _publisherEventDataRepository = serviceContext.GetRequiredService<IRepository<PublisherEventDataEntity>>();
        }

        public override async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            var now = DateTimeOffset.Now;

            var publisherEventDataEntitys = await _publisherEventDataRepository.GetSelectRepository().Where(a =>
                a.ExpireTime < now && a.ExpireTime != null
                && a.EventDataStatus == EventDataStatusEnum.Success
               ).ToListAsync(cancellationToken);

            foreach (var publisherEventDataEntity in publisherEventDataEntitys)
            {
                await _publisherEventDataRepository.RemoveAsync(publisherEventDataEntity, cancellationToken);
            }
            await _unitOfWorkManager.CommitAsync(cancellationToken);
        }
    }
}
